<?php

namespace app\common\logic;

use think\Db;
use think\Exception;

class UpdateHtmlOssLogic extends Logic
{
    static public function process()
    {
        //获取当前资源文件
        $localFileList = Db::name("oss_res")->select()->toArray();

        $fileArr = array();
        $static_file = ROOT_PATH . 'public/static';
        self::read_all_dir($static_file, $fileArr);

        self::checkFileExist($localFileList, $fileArr);

        //上传oss
        self::updateOss();

        //删除缓存
        deldir(RUNTIME_PATH . 'temp/');
    }

    /*
    * 同步oss
    */
    static function updateOss()
    {
        $enter = "<br/>" . PHP_EOL;
        $oss_res_db = Db::name('oss_res');
        $oss_log_db = Db::name('oss_log');

        $find = $oss_log_db->order("id desc")->find();
        if (empty($find)) {
            $list = $oss_res_db->select();
        } else {
            $where = array(
                'createtime' => array("gt", strtotime($find['updatetime'])),
            );
            $list = $oss_res_db->where($where)->select();
        }

        foreach ($list as $key => $value) {
            $url = $value['url'];
            $dst_url = config('aliyun.project_flag') . DS . str_replace(ROOT_PATH . 'public/', '', $url);
            $result = OssLogic::oss_file_upload(config('aliyun.static_endpoint'), config('aliyun.static_bucket'), $url, $dst_url);

            echo $dst_url . $enter;
            if (isset($result['code']) && $result['code'] == 0) continue;

            $item = array(
                'url' => $value['url'],
                'updatetime' => date("Y-m-d H:i:s", time()),
            );
            $oss_log_db->insert($item);
        }
    }

    /*
     * 遍历当前目录，获取当前目录下的所有文件
     * 排除php apk svn 等
     */
    static function read_all_dir($dir, &$fileArr)
    {
        $result = array();
        $handle = opendir($dir);
        if ($handle) {
            while (($file = readdir($handle)) !== false) {
                try {
                    if ($file != '.' && $file != '..') {
                        $file = iconv("UTF-8", "gb2312", $file);
                        $cur_path = $dir . DIRECTORY_SEPARATOR . $file;
                        if (!self::checkFilter($cur_path)) {
                            if (is_dir($cur_path)) {
                                self::read_all_dir($cur_path, $fileArr);
                            } else {
                                array_push($fileArr, $cur_path);
                            }
                        }
                    }
                } catch (Exception $e) {
                    trace($e->getMessage(), 'error');
                }
            }
            closedir($handle);
        }
        return $result;
    }

    protected static function checkFilter($path)
    {
        $filterArr = array(
            ".idea",
            ".php",
            ".html",
            ".htaccess",
            ".log",
            ".md",
            ".tpl",
            ".tpl",
            ".txt",
            "ThinkPHP",
            "uploads",
            "UMEditor",
            'Public/Tool',
            ".json",
            ".apk",
            ".svn",
            "ueditor/php",
            "csv",
            ".sh",
        );

        foreach ($filterArr as $value) {
            if (strpos($path, $value) !== false) {
                return true;
            }
        }

        return false;
    }

    /*
     * 检查文件是否存在
     */
    protected static function checkFileExist($localFileArr, $fileArr)
    {
        $oss_res_db = Db::name("oss_res");

        foreach ($fileArr as $file) {
            try {
                $state = false;
                $mtime = filemtime($file);
                foreach ($localFileArr as $localValue) {
                    if ($localValue['url'] == $file) {
                        if ($localValue['createtime'] < $mtime) {
                            $oss_res_db->where(array('id' => $localValue['id']))->update(['createtime' => $mtime]);
                        }
                        $state = true;
                        break;
                    }
                }

                if (!$state) {
                    $item = array(
                        'url' => $file,
                        'createtime' => $mtime,
                    );
                    $id = $oss_res_db->insertGetId($item);
                    if ($id > 0) {
                        $item['id'] = $id;
                        array_push($localFileArr, $item);
                    }
                }
            } catch (Exception $e) {
                trace($e->getMessage(), 'error');
            }
        }
    }
}